package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.Company;
//import com.zrwl.poscloud.base.entity.MerchantCompany;
import com.zrwl.poscloud.base.entity.Sequence;
//import com.zrwl.poscloud.base.enums.CompanyServerBusinessType;
import com.zrwl.poscloud.base.enums.EBusinessType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.holder.RequestHolder;
import com.zrwl.poscloud.commons.utils.HTTPUtils;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
//import com.zrwl.poscloud.xo.global.RequestConfig;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.CompanyMapper;
import com.zrwl.poscloud.xo.service.AdminService;
import com.zrwl.poscloud.xo.service.CompanyService;
import com.zrwl.poscloud.xo.service.SequenceService;
import com.zrwl.poscloud.xo.vo.CompanyAdminRVO;
import com.zrwl.poscloud.xo.vo.CompanyVO;
import com.zrwl.poscloud.xo.vo.SequenceVO;
import org.apache.http.client.config.RequestConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;

/**
 * <p>
 * 待办事项表 服务实现类
 * </p>
 *
 * @author xuzhixiang
 * @since 2019年6月29日10:31:44
 */
@Service
public class CompanyServiceImpl extends SuperServiceImpl<CompanyMapper, Company> implements CompanyService {

//    @Autowired
//    private RequestConfig requestConfig;
    @Autowired
    private CompanyService companyService;
//    @Autowired
//    private HouseService houseService;
//    @Autowired
//    private MerchantCompanyService merchantCompanyService;
    @Resource
    private CompanyMapper companyMapper;
    @Autowired
    private AdminService adminService;
    @Autowired
    private SequenceService sequenceService;
//    @Autowired
//    private ServerSyncRecordService serverSyncRecordService;

    @Override
    public IPage<Company> getPageList(CompanyVO companyVO) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        // 查询用户名
        if (StringUtils.isNotEmpty(companyVO.getKeyword()) && !StringUtils.isEmpty(companyVO.getKeyword().trim())) {
            queryWrapper.like("full_name", companyVO.getKeyword().trim()).or().like("short_name", companyVO.getKeyword().trim());
        }
        Page<Company> page = new Page<>();
        page.setCurrent(companyVO.getCurrentPage());
        page.setSize(companyVO.getPageSize());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        IPage<Company> pageList = companyService.page(page, queryWrapper);
        List<Company> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public IPage<CompanyVO> getPageListSimple(CompanyVO companyVO) {
        Page<CompanyVO> page = new Page<>();
        page.setCurrent(companyVO.getCurrentPage());
        page.setSize(companyVO.getPageSize());
        IPage<CompanyVO> pageList = companyMapper.getPageListSimple(page, companyVO);
        List<CompanyVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<Company> getAllList(CompanyVO companyVO) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<Company> list = companyService.list(queryWrapper);
        return list;
    }

    @Override
    public List<Company> getAllList() {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<Company> list = companyService.list(queryWrapper);
        return list;
    }

    @Override
    public Company getByCode(String companyCode) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_code", companyCode);
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<Company> list = companyService.list(queryWrapper);
        if (list.isEmpty()) {
            throw new RuntimeException("该商户不存在");
        }
        return list.get(0);
    }

//    @Override
//    public String addCompany(CompanyVO companyVO) {
//        Company company = new Company();
//        // 字段拷贝【将companyVO中的内容拷贝至Company】
//        BeanUtils.copyProperties(companyVO, company, SysConf.STATUS);
//        company.setCompanyCode(getCompanyCode());
//        company.setLocalHoldKey(0);//初始化默认不持有
//        company.setCardPwd(getEquipmentPassWord(company.getCompanyCode()));
//        company.setPosPwd(getCardAPassWord());
//        company.setLngLat("[0,0]");//给定定位默认值
//        company.insert();
//        companyVO.setCompanyCode(company.getCompanyCode());
//        companyVO.setUid(company.getUid());
////        ServerSyncRecordVO serverSyncRecordVO = new ServerSyncRecordVO();//新添加的商户下方server无法同步到数据这里需要特殊处理
////        serverSyncRecordVO.setObject(company);
////        serverSyncRecordVO.setCompanyUid(company.getUid());
////        serverSyncRecordVO.setSummary(CompanyServerBusinessType.basicInformationUpload.getName());
////        serverSyncRecordVO.setName(CompanyServerBusinessType.basicInformationUpload.getName());
////        serverSyncRecordVO.setType(CompanyServerBusinessType.basicInformationUpload.getServerBusinessType());
////        serverSyncRecordService.add(serverSyncRecordVO);
//        MerchantCompanyVO merchantCompany = new MerchantCompanyVO();
//        merchantCompany.setCompanyUid(company.getUid());
//        merchantCompany.setMerchantUid(companyVO.getMerchantUid());
//        merchantCompany.setLastMerchantUid(companyVO.getMerchantUid());
//        merchantCompany.setSummary("初始化创建商户");
//        merchantCompany.setAdminUid(adminService.getMe().getUid());
//        merchantCompanyService.add(merchantCompany);
//        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
//    }

//    @Override
//    public String editCompany(CompanyVO companyVO) {//此接口云不能使用云若要使用则需要对接口改造匹配对应数据上传下载
//        Company company = companyService.getById(companyVO.getUid());
//        BeanUtils.copyProperties(companyVO, company);
////        company.setUpdateTime(new Date());
//        company.updateById();
//        ServerSyncRecordVO serverSyncRecordVO = new ServerSyncRecordVO();//加入同步数据
//        if (company.getLocalHoldKey() == 0) {//不允许私自持有密钥
//            company.setCardPwd(null);
//            company.setPosPwd(null);
//            company.setStartDisk(0);
//        }
//        serverSyncRecordVO.setObject(company);
//        serverSyncRecordVO.setCompanyUid(company.getUid());
//        serverSyncRecordVO.setSummary(CompanyServerBusinessType.basicInformationUpload.getName());
//        serverSyncRecordVO.setName(CompanyServerBusinessType.basicInformationUpload.getName());
//        serverSyncRecordVO.setType(CompanyServerBusinessType.basicInformationUpload.getServerBusinessType());
//        serverSyncRecordService.add(serverSyncRecordVO);
//        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
//    }

//    @Override
//    public String deleteCompany(CompanyVO companyVO) {
//        Company Company = companyService.getById(companyVO.getUid());
//        Company.setStatus(EStatus.DISABLED);
////        Company.setUpdateTime(new Date());
//        Company.updateById();
//        MerchantCompany merchantCompany = merchantCompanyService.getOne(new QueryWrapper<MerchantCompany>().eq("company_uid", companyVO.getUid()).eq("status", 1));
//        merchantCompany.setStatus(EStatus.DISABLED);
////        merchantCompany.setUpdateTime(new Date());
//        merchantCompany.setAdminUid(adminService.getMe().getUid());
//        merchantCompany.setSummary("删除商户");
//        merchantCompany.updateById();
//        return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
//    }

//    @Override
//    public List<CompanyVO> getHouseList(CompanyVO companyVO) {
//        HttpServletRequest request = RequestHolder.getRequest();
//        String ownerUid = null;
//        if (request.getAttribute(SysConf.OWNER_UID) != null) {
//            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
//        }
//        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
//        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
//        queryWrapper.eq("uid", ownerUid);
//        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
//        List<Company> list = companyService.list(queryWrapper);
//        List<CompanyVO> resultList = new ArrayList<CompanyVO>();
//        for (int i = 0; i < list.size(); i++) {
//            Company entity = list.get(i);
//            CompanyVO vo = new CompanyVO();
//            BeanUtils.copyProperties(entity, vo);
//            HouseVO param = new HouseVO();
//            param.setCompanyUid(entity.getUid());
//            vo.setHouseList(houseService.getAllList(param));
//            resultList.add(vo);
//        }
//        return resultList;
//    }

    @Override
    public IPage<CompanyVO> getCurrentCompany(CompanyVO companyVO) {
        Page<CompanyVO> page = new Page<>();
        page.setCurrent(companyVO.getCurrentPage());
        page.setSize(companyVO.getPageSize());
        IPage<CompanyVO> pageList = companyMapper.getCurrentCompany(page, companyVO);
        List<CompanyVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<CompanyAdminRVO> getPresentCompany() {
        HttpServletRequest request = RequestHolder.getRequest();
        String ownerUid = null;
        if (request.getAttribute(SysConf.OWNER_UID) != null) {
            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
        }
        if (ownerUid != null) {
            Company company = companyService.getById(ownerUid);
            CompanyAdminRVO companyAdminRVO = new CompanyAdminRVO();
            companyAdminRVO.setCompanyCode(company.getCompanyCode());
            companyAdminRVO.setCompanyUid(company.getUid());
            companyAdminRVO.setCompanyName(company.getShortName());
            List<CompanyAdminRVO> list = new ArrayList<>();
            list.add(companyAdminRVO);
            return list;
        } else {
            return null;
        }
    }

    @Override
    public List<Company> getPresentCompanyMes(CompanyVO companyVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        String ownerUid = null;
        if (request.getAttribute(SysConf.OWNER_UID) != null) {
            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
        }
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.eq("uid", ownerUid);
        List<Company> list = companyService.list(queryWrapper);
        return list;
    }

    @Override
    public List<Company> getCompanyMesByUid(CompanyVO companyVO) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", companyVO.getUid());
        List<Company> companyList = companyService.list(queryWrapper);
        return companyList;
    }

    @Override
    public CompanyVO getCurrentCompanyInformation() {
        HttpServletRequest request = RequestHolder.getRequest();
        String ownerUid = null;
        if (request.getAttribute(SysConf.OWNER_UID) != null) {
            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
        }
        CompanyVO companyVO = companyMapper.getCurrentCompanyInformation(ownerUid);
        return companyVO;
    }

    //查询公司Uid接口
    @Override
    public String[] searchCompanyUid(String companyCode) {
        companyCode = "3333";
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("companyCode", companyCode);
        Company company = companyMapper.selectOne(queryWrapper);
        String companyUid = company.getUid();
        String companyName = company.getFullName();
        String[] companyUidAndName = {companyUid, companyName};
        return companyUidAndName;
    }

    @Override
    public List<Company> getCompanyMesByCodeAndName(CompanyVO companyVO) {
        List<Company> companyList = companyMapper.getCompanyMesByCodeAndName(companyVO);
        return companyList;
    }

    String getCompanyCode() {//60466175
        String code = "";
        SequenceVO sequenceVO = new SequenceVO();
        sequenceVO.setOwnerUid(null);
        sequenceVO.setOwnerType(0);//读取系统类型数据不确定
        sequenceVO.setCodeType(EBusinessType.companyCode);
        Sequence sequence = sequenceService.customizeSelect(sequenceVO);
        if (sequence.getNextCode() > 60466175) {
            throw new RuntimeException("数量超限");
        }
        Long number = Long.valueOf(sequence.getNextCode());
        String code36 = Long.toString(number, 36);
        for (int i = 0; i < (5 - code36.length()); i++) {
            code = '0' + code;
        }
        return code + code36;
    }

    String getEquipmentPassWord(String companyCode) {//FFFFFFFFFFFF
        String password = "";
        BigInteger bigInteger = new BigInteger(companyCode, 36);
        String companyCodeHex = Long.toHexString(Long.parseLong(String.valueOf(bigInteger)));
        password = password + companyCodeHex;
        for (int i = 0; i < (12 - companyCodeHex.length()); i++) {
            password = password + Integer.toHexString(new Random().nextInt(16));
        }
        return password.toUpperCase();
    }

    String getCardAPassWord() {//0000000000
        String password = "";
        for (int i = 0; i < 10; i++) {
            password = password + new Random().nextInt(10);
        }
        return password;
    }

//    public void getInitializationCompanyDataByCompanyCode() {
//        if (requestConfig.localMode) {
//            Company checkVO;
//            try {
//                checkVO = companyService.getByCode(requestConfig.companyCode);
//            } catch (Exception e) {
//                log.error(e.getMessage() + new Date());
//                checkVO = null;
//            }
//            if (checkVO == null) {
//                try {
//                    String address = requestConfig.cloudUrl + requestConfig.RequestInitializationCompanyDataUrl;
//                    Map<String, String> params = new HashMap<>();
//                    params.put("companyCode", requestConfig.companyCode);
//                    String res = HTTPUtils.post(address, params, null);
//                    res = res.substring(res.indexOf("{"));//截取
//                    String code = JSONObject.parseObject(res).getString("code");
//                    if (code.equals("success")) {
//                        Company entity = JSONObject.parseObject(JSONObject.parseObject(res).getString("data"), Company.class);
//                        entity.insertOrUpdate();
//                        log.debug("商户初始化基础数据处理完成" + "time:" + new Date());
//                    } else {
//                        throw new RuntimeException(JSONObject.parseObject(res).getString("message"));
//                    }
//                } catch (Exception e) {
//                    log.error(e.getMessage() + new Date());
//                    log.error("本地获取商户信息失败");
//                    System.exit(0);//正常关闭程序
//                }
//            }
//        }
//    }

}
